import pygame
from pygame.locals import *
from plane import *
import time
import random


def main():
    # 1.创建一个窗口，用来显示内容
    screen = pygame.display.set_mode((480, 800), 0, 32)

    # 2.创建一个和窗口大小的图片，用来充当背景
    image_file_path = './feiji/background.png'
    background = pygame.image.load(image_file_path).convert()

    # 3. 创建一个飞机对象
    hero_plane = HeroPlane(screen, "hero")

    # 4. 创建一个敌人飞机列表
    enemy_planes = []

    clock = pygame.time.Clock()
    # 添加时间变量
    last_fired = 0
    last_spawn = 0
    #
    hero_group = pygame.sprite.Group()
    hero_group.add(hero_plane)
    enemy_bullet_group=pygame.sprite.Group()
    enemy_bullet=EnemyBullet(screen,"enemy")
    enemy_bullet_group.add(enemy_bullet)

    # 4.把背景图片放到窗口中显示
    while True:
        screen.blit(background, (0, 0))
        hero_plane.display()

        # 生成敌机
        current_time = time.time()
        if current_time - last_spawn > 1:  # 每秒生成一次敌机
            num_enemies = random.randint(0,1)  # 随机生成敌机数量
            for _ in range(num_enemies):
                new_enemy = EnemyPlane(screen, "enemy")
                enemy_planes.append(new_enemy)
            last_spawn = current_time

        # 移动和发射子弹
        for enemy_plane in enemy_planes:
            enemy_plane.display()
            enemy_plane.move()
            enemy_plane.launch_bullet(enemy_bullet )

        # 判断是否是点击了退出按钮
        for event in pygame.event.get():
            if event.type == QUIT:
                print("exit")
                exit()

        keys = pygame.key.get_pressed()
        if keys[K_a] or keys[K_LEFT]:
            print('left')
            hero_plane.move_left()
        elif keys[K_d] or keys[K_RIGHT]:
            print('right')
            hero_plane.move_right()
        elif keys[K_w] or keys[K_UP]:
            print('upper')
            hero_plane.move_up()
        elif keys[K_s] or keys[K_DOWN]:
            print('down')
            hero_plane.move_down()

        # 添加子弹发射间隔
        if keys[K_SPACE]:
            current_time = time.time()
            if current_time - last_fired > 0.2:  # 间隔为0.2秒
                hero_plane.launch_bullet()
                last_fired = current_time
        pygame.sprite.groupcollide(hero_group, enemy_bullet_group, True, True)

        time.sleep(0.01)
        clock.tick(60)
        pygame.display.update()


if __name__ == '__main__':
    main()